package com.example.receiver;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DownloadFile extends Activity{
	
	Button download;
	TextView txt;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    Button startBtn;
    private ProgressDialog mProgressDialog;
    String URLDownload;
    EditText edturl;
    String Path;
    String url;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downloadfile);
		
		download = (Button) findViewById(R.id.btnDownload);
		txt = (TextView) findViewById(R.id.txtV);
		edturl = (EditText) findViewById(R.id.editdownload);
		
		url = getIntent().getStringExtra("urlvoice");
		
		edturl.setText( "http://172.16.149.122/myexample/"+url+".mp3");
		//URLDownload =	edturl.getText().toString();
		
	
		 if (android.os.Build.VERSION.SDK_INT >= 9) {
	            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	            StrictMode.setThreadPolicy(policy);
	        }
		 
		  download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			 startDownload();
				
			}
		});
		
	}

	private void startDownload() {
		Log.d("url",""+edturl.getText().toString());
		URLDownload =	edturl.getText().toString();
        new DownloadFileAsync().execute(URLDownload);
    }
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); //STYLE_SPINNER 
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

	
	class DownloadFileAsync extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... aurl) {
			// TODO Auto-generated method stub
			 int count;
			
			 try {
					
				    URL url = new URL(aurl[0]);
				    URLConnection conexion = url.openConnection();
				    conexion.connect();
				
				    int lenghtOfFile = conexion.getContentLength();
				    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
				
				    InputStream input = new BufferedInputStream(url.openStream());
				    
				    // Get File Name from URL
				    String fileName = URLDownload.substring( URLDownload.lastIndexOf('/')+1, URLDownload.length() );
				
				    OutputStream output = new FileOutputStream("/storage/extSdCard/data/"+fileName);
				    
				    byte data[] = new byte[1024];
				
				    long total = 0;
				
				        while ((count = input.read(data)) != -1) {
				            total += count;
				            publishProgress(""+(int)((total*100)/lenghtOfFile));
				            output.write(data, 0, count);
				        }
				
				        output.flush();
				        output.close();
				        input.close(); 
				        
				    } catch (Exception e) {}
					
				    return null;
		}

		@Override
		protected void onPostExecute(String result) {
			 super.onPostExecute(result);
			 dismissDialog(DIALOG_DOWNLOAD_PROGRESS);	
			 Intent gotonext = new Intent(DownloadFile.this,AudioVoice.class);
			 gotonext.putExtra("pathmusic",""+url.substring(7));
			 startActivity(gotonext);
			 
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showDialog(DIALOG_DOWNLOAD_PROGRESS);
			
			
		}

		@Override
		protected void onProgressUpdate(String... progress) {
			 super.onProgressUpdate(progress);
			 Log.d("ANDRO_ASYNC",progress[0]);
	         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
			
		} 

	}
	
	
	
}
